package cn.webrx.bs.servlet;

import cn.webrx.bs.entity.Link;
import cn.webrx.bs.service.LinkDao;
import cn.webrx.bs.service.LinkDaoImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <p>功能描述: </p>
 *
 * @author webrx
 * @version 1.0
 * @date 2020-08-05 11:22
 */
@WebServlet("/admin/link")
public class AdminLink extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String action = req.getParameter("action");
        if ("add".equals(action)) {
            String t = req.getParameter("title");
            String u = req.getParameter("url");
            String i = req.getParameter("isshow"); //如果没有选中，传null，如果选中传1
            Link link = new Link();
            link.setTitle(t);
            link.setUrl(u);
            link.setShows(i == null ? false : true);
            LinkDao linkdao = new LinkDaoImpl();
            int n = linkdao.add(link);
            resp.sendRedirect("/admin/link?action=manager");
        }else if("manager".equals(action)) {
            //req.setAttribute("links", new LinkDaoImpl().queryAll());

            LinkDaoImpl linkdao = new LinkDaoImpl();
            linkdao.pagesize = 1;
            int currpage = req.getParameter("p") == null ? 1 : Integer.parseInt(req.getParameter("p"));
            linkdao.pagecount = linkdao.count()%linkdao.pagesize == 0 ? linkdao.count()/linkdao.pagesize : linkdao.count()/linkdao.pagesize+1;
            linkdao.currpage = currpage;
            //req.setAttribute("pagecount",linkdao.count()%linkdao.pagesize == 0 ? linkdao.count()/linkdao.pagesize : linkdao.count()/linkdao.pagesize+1);
            //req.setAttribute("currpage",currpage);
            req.setAttribute("links",linkdao.page(currpage));
            req.setAttribute("pageinfo",linkdao.pageInfo());
            req.getRequestDispatcher("/admin/linkmanager.ftl").forward(req, resp);
        }else if("delall".equals(action)){
            LinkDao linkdao = new LinkDaoImpl();
            linkdao.delByIds(req.getParameter("ids"));
        }else if("delbyid".equals(action)){
            int id = Integer.parseInt(req.getParameter("id"));
            LinkDao linkdao = new LinkDaoImpl();
            linkdao.delById(id);
        }else if("shows".equals(action)){
            int id = Integer.parseInt(req.getParameter("id"));
            String shows = req.getParameter("shows");
            LinkDao linkdao = new LinkDaoImpl();
            linkdao.updateShows(id,"true".equals(shows));
        } else {
            req.getRequestDispatcher("/admin/link.ftl").forward(req, resp);
        }
    }
}
